package com.snail.snailvr.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

import com.snail.snailvr.VRApp;

/**
 * 网络集合类
 * Created by snail on 2016/4/20.
 */
public class NetworkUtil {

    public static final int TYPE_WIFI = 0, TYPE_MOBILE = 1, TYPE_NOT_CONNECTED = 2;
    public static int currentNetworkType = TYPE_MOBILE;
    public static int getConnectivityStatus(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null)
            return TYPE_MOBILE;
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (null != activeNetwork) {
            if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
                return TYPE_WIFI;

            if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
                return TYPE_MOBILE;
        }

        return TYPE_NOT_CONNECTED;
    }

    public static void refreshNetworkType(Context context){
        currentNetworkType = NetworkUtil.getConnectivityStatus(context);
    }
    public static boolean isWifiConnected(){
        return getConnectivityStatus(VRApp.getInstance())==TYPE_WIFI;
    }
    public static boolean isMobileDataConnected(){
        return getConnectivityStatus(VRApp.getInstance())==TYPE_MOBILE;
    }
    public static boolean isNetworkConnected(){
        return getConnectivityStatus(VRApp.getInstance())!=TYPE_NOT_CONNECTED;
    }

    public static boolean isNoConnected(){
        return getConnectivityStatus(VRApp.getInstance())==TYPE_NOT_CONNECTED;
    }

    public static String getIpAddress() {
        WifiManager wifiManager = (WifiManager) VRApp.getInstance().getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        int ipAddress = wifiInfo.getIpAddress();
        return formatIpAddress(ipAddress);
    }

    private static String formatIpAddress(int ipAdress) {
        return (ipAdress & 0xFF) + "." +
                ((ipAdress >> 8) & 0xFF) + "." +
                ((ipAdress >> 16) & 0xFF) + "." +
                (ipAdress >> 24 & 0xFF);
    }

    public static String getWifiName(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getSSID().replace('"', ' ');
    }
}
